module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('login_logs', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
        comment: '登录日志ID',
      },
      tenant_id: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'tenants',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        comment: '租户ID',
      },
      user_id: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'users',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
        comment: '用户ID',
      },
      username: {
        type: Sequelize.STRING(100),
        allowNull: false,
        comment: '登录用户名',
      },
      login_type: {
        type: Sequelize.ENUM('password', 'sms', 'wechat', 'oauth'),
        allowNull: false,
        defaultValue: 'password',
        comment: '登录方式',
      },
      status: {
        type: Sequelize.ENUM('success', 'failed'),
        allowNull: false,
        comment: '登录状态',
      },
      ip: {
        type: Sequelize.STRING(45),
        allowNull: true,
        comment: 'IP地址（支持IPv6）',
      },
      ip_location: {
        type: Sequelize.STRING(200),
        allowNull: true,
        comment: 'IP归属地',
      },
      user_agent: {
        type: Sequelize.STRING(500),
        allowNull: true,
        comment: '用户代理',
      },
      browser: {
        type: Sequelize.STRING(100),
        allowNull: true,
        comment: '浏览器',
      },
      os: {
        type: Sequelize.STRING(100),
        allowNull: true,
        comment: '操作系统',
      },
      device: {
        type: Sequelize.STRING(100),
        allowNull: true,
        comment: '设备类型',
      },
      fail_reason: {
        type: Sequelize.STRING(500),
        allowNull: true,
        comment: '失败原因',
      },
      login_time: {
        type: Sequelize.DATE,
        allowNull: false,
        comment: '登录时间',
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    });

    // 添加索引
    await queryInterface.addIndex('login_logs', ['tenant_id']);
    await queryInterface.addIndex('login_logs', ['user_id']);
    await queryInterface.addIndex('login_logs', ['username']);
    await queryInterface.addIndex('login_logs', ['status']);
    await queryInterface.addIndex('login_logs', ['ip']);
    await queryInterface.addIndex('login_logs', ['login_time']);
  },

  down: async (queryInterface) => {
    await queryInterface.dropTable('login_logs');
  },
};

